package com.atnjupt.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Wizarder
 * @create 2021-06-09 17:39
 */
public class SessionServlet extends BaseServlet{
    protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //session的创建request.getSession()，这个方法第一次是创建，后面都是获取
        HttpSession session = request.getSession();
        //判断该Session对象是否新创建的，true表示新建，false表示已经创建过的
        boolean isNew = session.isNew();
        //获取session对象的唯一id身份码
        String id = session.getId();
        response.getWriter().write("session对象创建了<br>" + "session是否新建："+ isNew+"<br>session的唯一身份码:" + id);
    }
    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("key1","value1");
        response.getWriter().write("session中存入数据");
    }
    protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object value1 = request.getSession().getAttribute("key1");
        response.getWriter().write("session的值：" + value1 );
    }
    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
        response.getWriter().write("默认的session会话时常:" + maxInactiveInterval);
    }
    protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setMaxInactiveInterval(3);
        response.getWriter().write("设置了session3秒销毁");
    }
    protected void destoryRightNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.getWriter().write("session立刻销毁");
    }

}
